package com.qd.push.config;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置  定时任务，异步任务
 *
 * @author sjk
 */
@Configuration
@EnableAsync
@EnableScheduling
@Slf4j
public class ExecutorConfig implements SchedulingConfigurer, AsyncConfigurer {
    @Resource
    private TaskExecutionProperties taskExecutionProperties;

    private static final Map<String, ExecutorService> MAP = new ConcurrentHashMap<>();

    /**
     * 异步任务执行线程池
     */
    @Bean(destroyMethod = "shutdown", name = "asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor() {
        int corePoolSize = taskExecutionProperties.getPool().getCoreSize();
        int queueCapacity = taskExecutionProperties.getPool().getQueueCapacity();
        long keepAliveSeconds = taskExecutionProperties.getPool().getKeepAlive().getSeconds();
        int maxPoolSize = taskExecutionProperties.getPool().getMaxSize();
        String threadNamePrefix = Optional.ofNullable(taskExecutionProperties.getThreadNamePrefix()).orElse("mq-http-Executor-");
        log.info("异步任务执行线程池初始化,corePoolSize: {},maxPoolSize: {},queueCapacity: {},keepAliveSeconds: {},threadNamePrefix: {}", corePoolSize, maxPoolSize, queueCapacity, keepAliveSeconds, threadNamePrefix);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds((int) keepAliveSeconds);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public void configureTasks(@NotNull ScheduledTaskRegistrar scheduledTaskRegistrar) {
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> log.error("异步任务执行出现异常, message {}, method {}, params {}", throwable, method, objects);
    }

    public ExecutorService getExecutorService(String type) {
        ExecutorService executorService = MAP.get(type);
        if(null == executorService){
            executorService = ThreadUtil.newExecutor(5, 30, 5000);
            MAP.put(type,executorService);
        }
        return executorService;
    }
}
